package com.herench.bunch.clinic.convert;


import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v24.group.ADR_A19_QUERY_RESPONSE;
import ca.uhn.hl7v2.model.v24.message.ADR_A19;
import ca.uhn.hl7v2.model.v24.message.QRY_A19;
import ca.uhn.hl7v2.model.v24.segment.*;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Iterator;

public class LoadRegistrationBarInformationConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgTpl(ProxyMsgCodeConstant.LOAD_REGISTRATION_BAR_INFORMATION_CODE);
        Element requestElement = document.getRootElement();
        QRY_A19 hl7 = (QRY_A19) requestMessage.getHl7Message();
        QRF qrf = hl7.getQRF();

        String ReceiptCode = qrf.getQrf1_WhereSubjectFilter(0).getValue();


        requestElement.addElement("ReceiptCode").addText(ReceiptCode!=null?ReceiptCode:"");

        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200230 from HIS XML = "+ message);
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        Element res = doc.getRootElement();
        ADR_A19 adrA19 = new ADR_A19();
        adrA19.initQuickstart("ADR_A19", "ADR_A19", "P");
        MSH msh = adrA19.getMSH();
        initResponseMessageMSH(msh);

        MSA msa = adrA19.getMSA();
        msa.getErrorCondition().getCe1_Identifier().setValue(doc.getRootElement().elementTextTrim("IsSuccessed"));
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().elementTextTrim("ErrorMsg"));


        ADR_A19_QUERY_RESPONSE queryResponse = adrA19.getQUERY_RESPONSE(0);
        PID pid = queryResponse.getPID();
        pid.getPid2_PatientID().getCx1_ID().setValue(res.elementTextTrim("HISPatientID"));
        pid.getPid2_PatientID().getCx2_CheckDigit().setValue(res.elementTextTrim("CureCardNo"));
        pid.getPid2_PatientID().getCx3_CodeIdentifyingTheCheckDigitSchemeEmployed().setValue(res.elementTextTrim("ApplyDeptName"));
        pid.getPid5_PatientName(0).getXpn2_GivenName().setValue(res.elementTextTrim("PatientName"));
        pid.getPid7_DateTimeOfBirth().getTs1_TimeOfAnEvent().setValue(res.elementTextTrim("Age"));
        pid.getPid8_AdministrativeSex().setValue(res.elementTextTrim("HISPatientSex"));
        pid.getPid11_PatientAddress(0).getXad2_OtherDesignation().setValue(res.elementTextTrim("PaymentType"));
        pid.getPid11_PatientAddress(0).getXad3_City().setValue(res.elementTextTrim("InsureTypeCode"));
        pid.getPid11_PatientAddress(0).getXad4_StateOrProvince().setValue(res.elementTextTrim("MtType"));
        pid.getPid11_PatientAddress(0).getXad5_ZipOrPostalCode().setValue(res.elementTextTrim("YZNumber"));
        pid.getPid11_PatientAddress(0).getXad6_Country().setValue(res.elementTextTrim("RegCode"));
        pid.getPid11_PatientAddress(0).getXad7_AddressType().setValue(res.elementTextTrim("ExecuteDeptName"));
        pid.getPid13_PhoneNumberHome(0).getXtn1_9999999X99999CAnyText().setValue(res.elementTextTrim("TotalMoney"));
        pid.getPid13_PhoneNumberHome(0).getXtn2_TelecommunicationUseCode().setValue(res.elementTextTrim("CashPay"));
        pid.getPid13_PhoneNumberHome(0).getXtn3_TelecommunicationEquipmentType().setValue(res.elementTextTrim("InsurePay"));
        pid.getPid13_PhoneNumberHome(0).getXtn4_EmailAddress().setValue(res.elementTextTrim("AccountPay"));
        pid.getPid13_PhoneNumberHome(0).getXtn5_CountryCode().setValue(res.elementTextTrim("OpTime"));
        pid.getPid13_PhoneNumberHome(0).getXtn6_AreaCityCode().setValue(res.elementTextTrim("OpName"));
        pid.getPid13_PhoneNumberHome(0).getXtn7_PhoneNumber().setValue(res.elementTextTrim("ReceiptCode"));
        pid.getPid13_PhoneNumberHome(0).getXtn8_Extension().setValue(res.elementTextTrim("TipMessages"));
        pid.getPid13_PhoneNumberHome(0).getXtn9_AnyText().setValue(res.elementTextTrim("Comment"));


        Element Items = res.element("Items");

        int index = 0;
        for (Iterator<Element> iterator0 = Items.elementIterator(); iterator0.hasNext(); ) {
            OBX obx = queryResponse.getOBX(index++);
            Element Item = iterator0.next();
            obx.getObx1_SetIDOBX().setValue(Item.elementTextTrim("PrescriptionCode"));
            obx.getObx2_ValueType().setValue(Item.elementTextTrim("PrescriptionName"));
            obx.getObx4_ObservationSubId().setValue(Item.elementTextTrim("ExecuteDeptName"));
            obx.getObx7_ReferencesRange().setValue(Item.elementTextTrim("YZNumber"));
            obx.getObx8_AbnormalFlags().setValue(Item.elementTextTrim("TotalAmount"));




            Element ItemLists = Item.element("ItemLists");
            int i = 0;
            for (Iterator<Element> iterator = ItemLists.elementIterator(); iterator.hasNext(); ) {

                Element ItemList = iterator.next();
                obx.getObx18_EquipmentInstanceIdentifier(i).getEi1_EntityIdentifier().setValue(ItemList.elementTextTrim("ItemName"));
                obx.getObx18_EquipmentInstanceIdentifier(i).getEi2_NamespaceID().setValue(ItemList.elementTextTrim("ItemSpecs"));
                obx.getObx18_EquipmentInstanceIdentifier(i).getEi3_UniversalID().setValue(ItemList.elementTextTrim("Number"));
                obx.getObx18_EquipmentInstanceIdentifier(i).getEi4_UniversalIDType().setValue(ItemList.elementTextTrim("Cost"));
                i++;
            }






        }
        return adrA19;
    }

    @Override
    public Message generatorReqMessage() throws Exception {
        QRY_A19 qbp = new QRY_A19();
        qbp.initQuickstart("QRY_A19", "QRY_A19", "A");
        MSH msh = qbp.getMSH();
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMessageControlID().setValue(IdGenerator.getUUID());
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200210");
        msh.getMsh11_ProcessingID().getProcessingMode().setValue("QR");
        msh.getMsh11_ProcessingID().getPt2_ProcessingMode().setValue("B206");


        QRF qrf =qbp.getQRF();

        qrf.getQrf1_WhereSubjectFilter(0).setValue("ReceiptCode");


        return qbp;
    }
}




